/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.source.network.converter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import retrofit2.Converter;

/**
 * @author Young Ken
 */
@SuppressWarnings("all")
public class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Gson mGson;
    private final TypeAdapter<T> mAdapter;

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.mGson = gson;
        this.mAdapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String jsonString = new String(value.bytes());
        MediaType contentType = value.contentType();
        Charset charset = contentType != null ? contentType.charset(Util.UTF_8) : Util.UTF_8;
        InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
        Reader reader = new InputStreamReader(inputStream, charset);
        JsonReader jsonReader = mGson.newJsonReader(reader);

        try {
            return mAdapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
